//
//  ST_RectangleLoveMeController.swift
//  btvideo
//
//  Created by mac on 2020/9/19.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import MJRefresh
import SwiftyJSON
import SwiftyAttributes
import NIMSDK
import SwiftyUserDefaults


class ST_RectangleLoveMeController: UIViewController{
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = Color.clear
        
         
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            self.refresh_data()
        })
        
        view.addSubview(unlock_btn)
        unlock_btn.snp.makeConstraints { (make) in
            make.width.equalTo(260)
            make.height.equalTo(44)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-49-20-BTSafeAreaBottom)
        }
        
        binding()
        
    }
    
    private func binding(){
        
        NotificationCenter.default.addObserver(self, selector: #selector(showed_noti_handle(noti:)), name: Notification.Name.showedSomeOne, object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(refresh_data), name: NSNotification.Name.refresh_love_me, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(refresh_data), name: Notification.Name.in_pur_status_success, object: nil)
        
        SCComponets.login_status_did_changed_observable().distinctUntilChanged().withUnretained(self).subscribe(onNext: { own,f in
            print("SCComponets.login_status_did_changed_observable()")
            if f == true{
                own.refresh_data()
            }else{
                own.clear_data()
            }
            
        }).disposed(by: rx.disposeBag)
    }
    
    @objc fileprivate func showed_noti_handle(noti:Notification){
        
        guard let info = noti.userInfo ,let vc = info["fromController"] as? UIViewController ,let id = info["id"] as? String else{
            return
        }
        
        
        let found = self.data_array.removeFirst(where: {($0.accid == id)})
        
        
        if found != nil{
            
            self.unread_like_number -= 1
            if self.unread_like_number < 0{
                self.unread_like_number = 0
            }
            
            self.collectionView.reloadData()
            
            self.empty_view_handle()
        }
        
    }
    
    
    @objc func refresh_data(){
        
        self.currentPage = 0
        self.request_data()
        
    }
    
    
    @objc func clear_data(){
        
        
        UNREAD_LOVE_OF_MEET = 0
        
        data_array.removeAll()
        
        self.collectionView.reloadData()
        
        self.collectionView.mj_footer?.endRefreshing()
    }
    
    func request_data(){
        
        guard let token = ST_BTUserInfoManager.shared.current_account_info?.token,  token.count > 1 else{
            
            clear_data()
            
            return
        }
        
        
        currentPage += 1
        
        var param = ["page":currentPage,
                     "size":pageSize] as [String : Any]
        
        ST_ChatModuleViewController.shared.curr_filter.conver_to_param().forEach { (item) in
            param.updateValue(item.value, forKey: item.key)
        }
        
        
        JVrequest(PH.likeIndexApi,parameters:param, success: { (json) in
            
            
            
            
            let data = json["data"]["list"]
            
            self.unread_like_number = json["data"]["count"].intValue
            
            //            print("收到的喜欢数据：",json)
            
            var array = [ST_PairsLoveItemViewModel]()
            
            for item in data.arrayValue{
                
                if let model = ST_PairsLoveItemViewModel.deserialize(from: item.dictionaryObject){
                    
                    let albumList = ST_PairsShareParticularModel.describe(json_array: item["album"].arrayValue)
                    
                    model.album = albumList
                    
                    array.append(model)
                }
            }
            
            if self.currentPage == 1{
                self.data_array = array
            }else{
                self.data_array += array
            }
            
            self.collectionView.reloadData()
            
            self.empty_view_handle()
            
            self.load_more_option_style(tableView: self.collectionView, count: array.count, pageSize: self.pageSize) {
                
                self.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in
                    
                    if FETCH_MEMBER_STATUS() != .subscribe && ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male {
                        self?.popup_membership_controller()
                        self?.collectionView.mj_footer?.endRefreshing()
                    }else{
                        self?.request_data()
                    }
                    
                })
            }
            
            self.collectionView.mj_footer?.endRefreshing()
            self.collectionView.mj_header?.endRefreshing()
            
        }) { (code, err) in
            
            self.hidden_indeterminate_h_u_d()
            
            self.currentPage -= 1
            
            self.collectionView.mj_footer?.endRefreshing()
            self.collectionView.mj_header?.endRefreshing()
            
            ToastHud(text: err, view: self.view)
        }
        
    }
    
    @objc fileprivate func popup_membership_controller(){
        
        ST_MaidWayManager.shared.source = .遇见_喜欢了我
        
        
        let vc  = ST_MemberSubscriberController.init(subscribeType: ST_BitianSubscribeType.查看谁喜欢我)
        
        vc.overCurrentContext = true
        
        GlobalPresent(toController: vc, animated: false)
    }
    
    fileprivate func empty_view_handle(){
        
      
        
        if self.data_array.count < 1{
            
            let control = ST_BTEmptyView.init(title: "添加我的特质，收到喜欢几率立刻增加2倍！", imageName: ST_ImageUtils.imageName("喜欢_img_喜欢(空)")!, btnTitle: "添加特质") {
                
                push_to_push_peculiarity_controller(navigationController: self.navigationController)
            }
            
            self.collectionView.show_bitian_empty(view: control)
            
            self.unlock_btn.isHidden = true
            
        }else{
            
            
            //        男的 不是会员 加蒙层
            if FETCH_MEMBER_STATUS() != .subscribe && ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male {
                self.unlock_btn.isHidden = false
            }else{
                self.unlock_btn.isHidden = true
            }
            
            self.collectionView.hidden_bitian_empty_view()
        }
    }
    
    //    MARK:- Properties
    
    
    
    var currentPage = 0
    
    fileprivate var data_array = [ST_PairsLoveItemViewModel]()
    
    fileprivate var pageSize = 15
    
    fileprivate var unread_like_number = 0{
        didSet{
            
            if unread_like_number > 0{
                
                NotificationCenter.default.post(Notification(name: Notification.Name.love_me_red_point))
            }
        }
    }
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
        let controlLayout = UICollectionViewFlowLayout()
        controlLayout.minimumLineSpacing = 15
        controlLayout.minimumInteritemSpacing = 15
        controlLayout.sectionInset = UIEdgeInsets.init(top: 12, left: 15, bottom: BTSafeAreaBottom + 49, right: 15)
        let w = (ScreenWidth - 15*3)/2
        controlLayout.itemSize = CGSize.init(width: w, height: w/165*160+70)
        controlLayout.headerReferenceSize = CGSize.init(width: ScreenWidth, height: 40)
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_RectangleLoveMeCell.self)
        
        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: RectangleLoveMeHeaderView.self)
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.backgroundColor = Color.init(hexString: "#F5F8FA")
        control.alwaysBounceVertical = true
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
    
    
    
    fileprivate lazy var unlock_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        control.setTitle("查看谁喜欢我", for: UIControl.State.normal)
        control.setTitleColor(UIColor.white, for: UIControl.State.normal)
        control.setBackgroundImage(UIImage.init(color: UIColor.init(hex: 0xFEC207)!, size: CGSize.init(width: 1, height: 1)), for: UIControl.State.selected)
        control.setBackgroundImage(UIImage.init(color: UIColor.init(hex: 0xDFE3E9)!, size: CGSize.init(width: 1, height: 1)), for: UIControl.State.normal)
        control.isSelected = true
        control.cornerRadius = 22
        control.isHidden = true
        //      control.semanticContentAttribute = .forceRightToLeft
        control.addTarget(self, action: #selector(popup_membership_controller), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
}

// MARK: UICollectionViewDataSource
extension ST_RectangleLoveMeController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    
    
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_RectangleLoveMeCell.self, for: indexPath)
        
        cell.model = data_array[safe:indexPath.item]
        
        return cell
    }
    
    // MARK: UICollectionViewDelegate
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        //        男的 不是会员 加蒙层
        if FETCH_MEMBER_STATUS() != .subscribe && ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male {
            return
        }
        
        guard let m = data_array[safe:indexPath.item] else{
            return
        }
        
        let vc = ST_PairsCenterViewController()
        
        vc.accid = m.accid
        
        vc.from_receive_love = true
        
        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav)
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: RectangleLoveMeHeaderView.self, for: indexPath)
        
        if unread_like_number < 1{
            
            view.content_label.attributedText = NSAttributedString()
            
            return view
        }
        
        var s = "有".withAttributes([Attribute.font(Font.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)),Attribute.textColor(UIColor.init(hex: 0x333333)!)])
        
        let n = unread_like_number.string.withAttributes([Attribute.font(Font.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)),Attribute.textColor(UIColor.init(hex: 0xFEC207)!)])
        
        
        let p = "人喜欢了我".withAttributes([Attribute.font(Font.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)),Attribute.textColor(UIColor.init(hex: 0x333333)!)])
        
        s += n
        s += p
        
        view.content_label.attributedText = s
        
        return view
    }
    
}



//MARK: - Cell
class ST_RectangleLoveMeCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.backgroundColor = Color.white
        
        contentView.addSubview(cover_image_view)
        contentView.addSubview(gradient_view)
        contentView.addSubview(titleLabel)
        contentView.addSubview(content_label)
        contentView.addSubview(chat_btn)
        contentView.addSubview(sign_for_me_btn)
        
        contentView.addSubview(time_label)
        
        contentView.cornerRadius = 20
        
        cover_image_view.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(cover_image_view.snp.width).dividedBy(165.0/160.0)
        }
        
        gradient_view.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.height.equalTo(40)
            make.bottom.equalTo(cover_image_view)
        }
        
        time_label.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(cover_image_view).offset(-5)
        }
        
        
        
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(cover_image_view.snp.bottom).offset(13)
            make.height.equalTo(17)
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10-30-5)
        }
        
        
        content_label.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom).offset(8)
            make.left.equalTo(titleLabel)
            make.right.equalToSuperview().offset(-10-30-5)
        }
        
        chat_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(30)
            make.centerY.equalTo(titleLabel.snp.bottom)
            make.right.equalToSuperview().offset(-10)
        }
        
        sign_for_me_btn.snp.makeConstraints { (make) in
            make.left.top.equalToSuperview().offset(8)
            make.height.equalTo(22)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //    MARK: - Properties
    
    fileprivate lazy var cover_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.clipsToBounds = true
        return control
    }()
    
    fileprivate lazy var sign_for_me_btn:ST_RecommendForYouCellSignView = {
        let control = ST_RecommendForYouCellSignView()
        control.alpha = 0
        return control
    }()
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.init(hexString: "#333333")
        //        control.numberOfLines = 0
        //        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        return control
    }()
    
    
    fileprivate lazy var time_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.white
        //        control.numberOfLines = 0
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        return control
    }()
    
    
    fileprivate lazy var gradient_view:ST_FWGradientView = {
        let control = ST_FWGradientView()
        
        control.bgLayer.colors = [UIColor(red: 0.12, green: 0.12, blue: 0.12, alpha: 0).cgColor, UIColor(red: 0, green: 0, blue: 0, alpha: 0.4).cgColor]
        control.bgLayer.locations = [0, 1]
        control.bgLayer.startPoint = CGPoint(x: 0, y: 0)
        //        [UIColor(red: 0.12, green: 0.12, blue: 0.12, alpha: 0).cgColor, UIColor(red: 0.02, green: 0.02, blue: 0.02, alpha: 0.2).cgColor, UIColor(red: 0, green: 0, blue: 0, alpha: 0.4).cgColor]
        
        control.bgLayer.endPoint = CGPoint(x: 0, y: 1)
        return control
    }()
    
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.init(hexString: "#61666F")
        //        control.numberOfLines = 0
        //        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.medium)
        return control
    }()
    
    
    fileprivate lazy var chat_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("love_me_icon_mid")!)
        control.add_touch_up(insideTarget: self, action: #selector(chat_handle))
        return control
    }()
    
    fileprivate var visual_effect_view:ST_CustomIntensityVisualEffectView?
    
    func create_visual_effect()  {
        
        remove_visual_effect()
        
        let control = ST_CustomIntensityVisualEffectView.init(effect: UIBlurEffect(style: .light), intensity: 0.2)
        
        contentView.insertSubview(control, belowSubview: time_label)
        
        control.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        visual_effect_view = control
    }
    
    func remove_visual_effect()  {
        
        visual_effect_view?.removeFromSuperview()
        
    }
    
    //    MARK:-
    weak var model:ST_PairsLoveItemViewModel?{
        didSet{
            
            guard let m = model else{
                return
            }
            
            //            男的 不是会员 加蒙层
            if FETCH_MEMBER_STATUS() != .subscribe && ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male {
                create_visual_effect()
            }else{
                remove_visual_effect()
            }
            
            if m.props_integral > 0{
                sign_for_me_btn.alpha = 1
                sign_for_me_btn.bindGift()
            }else{
                sign_for_me_btn.alpha = 0
            }
            
            cover_image_view.pin_setImage(from: m.album.first?.imageUrl.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            titleLabel.text = m.nickname
            
            time_label.text = m.online_state
            
            content_label.text = m.age.string + "岁" + " \(m.address)"
        }
    }
    
}

//MARK: - Event
//
extension ST_RectangleLoveMeCell{
    
    @objc func chat_handle(){
        
        guard let m = model else{
            return
        }
        
        let avatar = m.album.first?.imageUrl ?? ""
        
        self.chat_btn.isUserInteractionEnabled = false
        
        PairsLikeAction(info: ST_MatchUserInfo.init(accid: m.accid, avatar: avatar, nickname: m.nickname), likeAction: true, isReceive: true, fromVC: self.parentViewController) { (code, err, matched) in
            
            self.chat_btn.isUserInteractionEnabled = true
            
            if code == 1{
                
                matched?()
                
                
                
                
            }else {
                
                if let e = err{ self.parentViewController?.toast(text: e) }
                
            }
            
        }
        
    }
}



class RectangleLoveMeHeaderView: UICollectionReusableView {
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.centerY.equalToSuperview()
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    lazy var content_label:UILabel = {
        let control = UILabel.init()
        return control
    }()
    
}
